<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <%
        String bathPath = request.getContextPath();
        pageContext.setAttribute("bathPath", bathPath);
    %>
    <meta charset="UTF-8">
    <title>统计图表</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" href="${bathPath}/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${bathPath}/css/common.css">
    <link rel="stylesheet" href="${bathPath}/css/formSelects-v4.css">
    <link rel="stylesheet" href="${bathPath}/css/holiday.css">
    <link rel="stylesheet" href="${bathPath}/css/statistical.css">
    <style type="text/css">
        #test1,#test2{
            width:150px;
        }
    </style>
</head>
<body>
<div class="holiday">
    <div class="layui-form demoTable">
        <div class="layui-inline">
            <label class="layui-form-label">部门</label>
            <div class="layui-input-inline">
                <select type="text" id="depId" name="depId" lay-verify="required" lay-filter="business"
                        autocomplete="off" class="layui-input">
                </select>
            </div>
        </div>

        <div class="layui-inline">
            <label class="layui-form-label">员工</label>
            <div class="layui-input-inline">
                <select type="text" id="userName" xm-select="userName" xm-select-show-count="1" xm-select-direction="down" lay-filter="userName" name="userName" lay-verify="required" autocomplete="off"
                        class="layui-input">
                </select>
            </div>
        </div>

        <div class="layui-inline">
            <label class="layui-form-label">起止时间</label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" name="test1" id="test1" placeholder="请选择开始日期" autocomplete="off">
            </div>
            <span class="separator">-</span>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" name="test2" id="test2" placeholder="请选择结束日期">
            </div>
        </div>

<%--        <div class="layui-inline" style="margin: 20px 0 0 0;">--%>
<%--            <label class="layui-form-label">排序</label>--%>
<%--            <div class="layui-input-inline">--%>
<%--                <input type="checkbox" name="sort" value="0" lay-skin="primary" title="部门">--%>
<%--                <input type="checkbox" name="sort" value="1" lay-skin="primary" title="登记号码">--%>
<%--                <input type="checkbox" name="sort" value="2" lay-skin="primary" title="姓名">--%>
<%--                <input type="checkbox" name="sort" value="3" lay-skin="primary" title="时间">--%>
<%--                <input type="checkbox" name="sort" value="4" lay-skin="primary" title="倒序">--%>
<%--            </div>--%>
<%--        </div>--%>

        <div class="layui-inline">
            <button class="layui-btn layui-btn-normal w92" data-type="reload" id="select">查询</button>
        </div>
    </div>
    <div class="layui-tab layui-tab-card" lay-filter="filter">
        <ul class="layui-tab-title">
            <li class="layui-this">统计结果明细情况</li>
            <li>班次明细情况</li>
            <li>其他异常情况</li>
            <li>考勤统计汇总</li>
            <li>未排班人员统计</li>
        </ul>
        <div class="layui-tab-content" style="height: auto;">
            <div class="layui-tab-item layui-show site-demo">
                <table class="layui-hide" id="holiday" lay-filter="test"></table>
            </div>
            <div class="layui-tab-item site-demo">
                <table class="layui-hide" id="gradeDetail" lay-filter="gradeDetail"></table>
            </div>
            <div class="layui-tab-item site-demo">
                <table class="layui-hide" id="other" lay-filter="other"></table>
            </div>
            <div class="layui-tab-item site-demo">
                <table class="layui-hide" id="attendTotal" lay-filter="attendTotal"></table>
            </div>
            <div class="layui-tab-item site-demo">
                <table class="layui-hide" id="unSchedule" lay-filter="unSchedule"></table>
            </div>
        </div>
    </div>
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>
</div>

<!--添加弹出层-->
<div id="addMask" style="display: none;">
    <form class="layui-form setting-holiday" action="#" id=runForm" lay-filter="example">
        <input type="hidden" id="userID" name="userID">
        <input type="hidden" id="checkTime" name="checkTime">
        <div class="layui-form-item">
            <label class="layui-form-label">出勤状态</label>
            <div class="layui-input-inline">
                <select name="editStatus">
                    <option value=""></option>
                    <option value="0">上班签到</option>
                    <option value="1">下班签退</option>
                    <option value="2">外出</option>
                    <option value="3">返回</option>
                    <option value="4">加班签到</option>
                    <option value="5">加班签退</option>
                    <option value="6">内开门</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button lay-submit class="layui-btn layui-btn-normal" lay-filter="formTest">确定</button>
                <button type="button" class="layui-btn layui-btn-primary cancel-layer">取消</button>
            </div>
        </div>
    </form>
</div>

</body>
<script src="${bathPath}/layui/layui.js" charset="utf-8"></script>
<script type="text/javascript" src="${bathPath}/js/jquery-1.9.1.min.js"></script>
<script src="${bathPath}/js/formSelects-v4.min.js"></script>
<script src="${bathPath}/js/common.js" type="text/javascript"></script>
<script>
    var layerIndex = null;
    var ids = ['statisticalRecords', 'gradeDetail', 'other', 'attendTotal', 'unSchedule'];
    var filterName = 'filter';
    var params = [
        {
            id: 'statisticalRecords',
            elem: '#holiday',
            url: '${bathPath}/checkInOut/selectAll.action',
            title: '统计结果明细情况表',
            height: 'full-89',
            tableId: 'statisticalRecords',
            cols: [
                {field: 'userName', title: '姓名', width: 100,sort: true}
                , {
                    field: 'depName', title: '部门',sort: true,minWidth: 100
                }
                , {field: 'userID', title: '登记号码',sort: true,minWidth: 180}
                , {field: 'checkTime', title: '出勤时间',sort: true,minWidth: 180}
                , {
                    field: 'checkType', title: '出勤状态',minWidth: 110
                }
                , {
                    field: 'editStatus', title: '更正状态',minWidth: 120
                }
                , {
                    field: 'otherStatus', title: '异常情况',minWidth: 120
                }
                , {toolbar: '#barDemo', title: '操作',minWidth:150}
            ]
            ,parseData: function(res){ //res 即为原始返回的数据
                $.each(res.data,function(i,item){
                    res.data[i].checkType= formatterAttendStatus(item.checkType);
                    res.data[i].editStatus= formatterAttendStatus(item.editStatus);
                    res.data[i].checkTime= formatTime(item.checkTime);
                    res.data[i].otherStatus= formatterOtherStatus(item.otherStatus);
                })
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.count, //解析数据长度
                    "data": res.data//解析数据列表
                };

            }
        },
        {
            id: 'gradeDetail',
            elem: '#gradeDetail',
            height: 'full-89',
            url: '${bathPath}/numRun/findNumRunBean.action',
            title: '班次明细情况表',
            tableId: 'gradeDetail',
            cols: [
                {field: 'userId', title: '序号', width: 90,sort: true},
                {field: 'userId', title: '登记号码',width:180,sort: true},
                {field: 'userName', title: '姓名', width: 90,sort: true},
                {field: 'depName', title: '部门',width:90,sort: true},
                {field: 'numRunNo', title: '排班序号',minWidth:120,sort: true},
                {field: 'autoSchPlan', title: '是否智能排班',minWidth:140,sort: true},
                {field: 'startTimeStr', title: '日期', width: 120},
                {field: 'name', title: '班次', width: 101},
                {field: 'runStartTime', title: '开始时间', width: 170},
                {field: 'runEndTime', title: '结束时间', width: 170},
                {field: 'schName', title: '对应时段', width: 101},
                // {field: 'cycle', title: '周期数', width: 101},
                // {field: 'units', title: '周期单位', width: 101},
                {field: 'schStartTimeStr', title: '上班时间',sort: true, minWidth: 180},
                {field: 'schEndTimeStr', title: '下班时间',sort: true, minWidth: 180},
                {field: 'checkInTime1Str', title: '签到时间',sort: true, minWidth: 180},
                {field: 'checkOutTime1Str', title: '签退时间',sort: true, minWidth: 180},
                {field: 'checkInTime2Str', title: '迟到时间',sort: true, minWidth: 180},
                {field: 'checkOutTime2Str', title: '早退时间',sort: true, minWidth: 180},
                {field: 'allWorkTime', title: '工作时间', minWidth: 180},
                {field: 'attendanceTime', title: '出勤时间', minWidth: 180},
                // {field: 'lateArrive', title: '迟到（次）',minWidth:120},
                // {field: 'leaveEarly', title: '早退（次）',minWidth:120},
                {field: 'absenteeism', title: '是否旷工',minWidth:120},
                {field: 'addWorkTime', title: '加班（分钟）',minWidth:173},
                {field: 'leaveName', title: '例外情况', minWidth: 180},
                {field: 'symbol', title: '表示符号', minWidth: 180},
                // {field: 'checkIn', title: '必须签到', width: 92},
                // {field: 'checkOut', title: '必须签退', width: 92}
            ]
            ,parseData: function(res){ //res 即为原始返回的数据
                $.each(res.data,function(i,item){
                    res.data[i].autoSchPlan= yesOrNo(item.autoSchPlan);
                    res.data[i].checkIn= yesOrNo(item.checkIn);
                    res.data[i].checkOut= yesOrNo(item.checkOut);
                    res.data[i].absenteeism= yesOrNo(item.absenteeism);
                    res.data[i].runStartTime= formatTime(item.runStartTime);
                    res.data[i].runEndTime= formatTime(item.runEndTime);
                    res.data[i].units= formatterCycleType(item.units);
                })
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.count, //解析数据长度
                    "data": res.data//解析数据列表
                };
            }
        },
        {
            id: 'other',
            elem: '#other',
            height: 'full-89',
            url: '${bathPath}/accessLog/selectError.action',
            title: '其他异常情况表',
            tableId: 'other',
            cols: [
                {field: 'userName', title: '姓名',sort: true,width:100}
                , {field: 'userId', title: '登记号码',sort: true,width:180}
                , {field: 'startTimeStr', title: '开始时间',sort: true, width: 162}
                , {field: 'endTimeStr', title: '结束时间',sort: true, width: 162}
                ,{field: 'timeSum', title: '总时长',width:100}
                ,{field: 'dayTime', title: '考勤日期',width:180}
                ,{field: 'leaveName', title: '异常',width:100}
                ,{field: 'tims', title: '有效时长',width:100}
                ,{field: 'days', title: '排班工作日',minWidth:180}
            ]
        },
        {
            id: 'attendTotal',
            elem: '#attendTotal',
            height: 'full-89',
            url: '${bathPath}/accessLog/selectCount.action',
            title: '考勤统计汇总表',
            tableId: 'attendTotal',
            cols: [
                {field: 'depName', title: '部门',sort: true,minWidth:120},
                {field: 'autoID', title: '序号',sort: true,minWidth:120},
                {field: 'userId', title: '登记号码',sort: true,minWidth:120},
                {field: 'userName', title: '姓名',sort: true,minWidth:120},
                // {field: 'name', title: '班次',sort: true,minWidth:120},
                // {field: 'runStartTime', title: '开始时间',minWidth:173},
                // {field: 'runEndTime', title: '结束时间',minWidth:173},
                {field: 'schName', title: '时段',sort: true,minWidth:120},
                // {field: 'cycle', title: '周期数',sort: true,minWidth:120},
                // {field: 'units', title: '周期单位',sort: true,minWidth:120},
                {field: 'shouldArrive', title: '应到（次）',minWidth:120},
                {field: 'trueArrive', title: '实到（次）',minWidth:120},
                {field: 'lateArrive', title: '迟到（次）',minWidth:120},
                {field: 'leaveEarly', title: '早退（次）',minWidth:120},
                {field: 'absenteeism', title: '旷工（次）',minWidth:120},
                {field: 'signIn', title: '签到（次）',minWidth:120},
                {field: 'signBack', title: '签退（次）',minWidth:120},
                {field: 'noSignIn', title: '未签到（次）',minWidth:120},
                {field: 'noSignBack', title: '未签退（次）',minWidth:120},
                {field: 'workMinsToDou', title: '工作时间（小时）',minWidth:173},
                {field: 'addWorkTime', title: '加班（小时）',minWidth:173},
                {field: 'isOut', title: '外出（小时）',minWidth:173},
                // {field: 'goOut', title: '公出（次）',minWidth:173},
                {field: 'leaveClass', title: '请假（小时）',minWidth:173},
                // {field: 'sickLeave', title: '病假（小时）',minWidth:173},
                // {field: 'thingLeave', title: '事假（小时）',minWidth:173},
                // {field: 'familyLeave', title: '探亲假（小时）',minWidth:173},
                {field: 'weekday', title: '平日（工作日）',minWidth:173},
                {field: 'weekend', title: '周末（工作日）',minWidth:173},
                {field: 'holiday', title: '节假日（工作日）',minWidth:173},
                {field: 'attendanceTime', title: '出勤时间（小时）',minWidth:173},
                {field: 'weekdayAddTime', title: '平日加班（小时）',minWidth:173},
                {field: 'weekendAddTime', title: '周末加班（小时）',minWidth:173},
                {field: 'holidayAddTime', title: '节假日加班（小时）',minWidth:173},
                // {field: 'cardSN', title: '卡号',minWidth:120}
            ]
            ,parseData: function(res){ //res 即为原始返回的数据
                $.each(res.data,function(i,item){
                    res.data[i].runStartTime= formatTime(item.runStartTime);
                    res.data[i].runEndTime= formatTime(item.runEndTime);
                    res.data[i].units= formatterCycleType(item.units);
                })
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.count, //解析数据长度
                    "data": res.data//解析数据列表
                };
            }
        },
        {
            id: 'unSchedule',
            elem: '#unSchedule',
            height: 'full-89',
            url: '${bathPath}/userOfRun/findNoUserOfRun.action',
            title: '未排班人员统计表',
            tableId: 'unSchedule',
            cols: [
                {field: 'userName', title: '姓名'}
                ,{field: 'userId', title: '登记号码'}
                ,{field: 'eDDate', title: '日期'}
            ]
            ,parseData: function(res){ //res 即为原始返回的数据
                $.each(res.data,function(i,item){
                    res.data[i].eDDate= formatterCycleType(item.eDDate);
                })
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.count, //解析数据长度
                    "data": res.data//解析数据列表
                };
            }
        }
    ];



    $(function () {
        initTableHead();
        initLayUI();
        $.ajax({
            type: "POST",
            async: false,
            data: "",
            url: "${bathPath}/dept/selectDpetName.action",
            success: function (msg) {
                var html = "";
                html += "<option value=''>" + '请选择' + "</option>";
                for (var i = 0; i < msg.length; i++) {
                    html += "<option value='" + msg[i].depID + "'>" + msg[i].depName + "</option>";
                }
                $("#depId").html(html);
            }
        });
    })

    function initTableHead(){
        var cols = [];//动态表头数组
        // 动态获取表头数据
        $.ajax({
            type: "POST",
            async: false,
            data: "",
            url: "${bathPath}/leaveClass/selectLeaveClassName.action",
            success: function (data) {
                var fieldsArr = [];
                for(var i = 0; i <data.length;i++ ){
                    var fields = 'holoday'+data[i].id;
                    var unit = data[i].unit;
                    var labelName = null;
                    if(unit === 1){
                        labelName = '(小时)';
                    }else if(unit === 2){
                        labelName = '(分钟)';
                    }else if(unit === 3){
                        labelName = '(工作日)';
                    }
                    var title = data[i].leaveName+labelName;
                    cols[i] = {
                        field:fields
                        ,title:title
                        ,minWidth: 173
                    }
                    fieldsArr.push(fields);
                    params[3].cols.splice(18+i,0,cols[i]);
                }
                params[3].parseData = function(res){
                    $.each(res.data,function(j,item){
                        var resData = res.data[j];
                        var list = resData.list;
                        if(list === null || (list && list.length === 0)){
                            for(var k = 0;k < fieldsArr.length; k++){
                                resData[fieldsArr[k]] = 0;
                            }
                        }else if(list && list.length > 0){
                            var obj = attrValueAdd(list);
                            for(var m = 0;m < fieldsArr.length; m++ ){
                                if(obj[fieldsArr[m]] && obj[fieldsArr[m]] !== null && Object.keys(obj[fieldsArr[m]]).length > 0){
                                    resData[fieldsArr[m]] = obj[fieldsArr[m]].value;
                                }else{
                                    resData[fieldsArr[m]] = 0;
                                }
                            }
                        }
                        res.data[j].eDDate= formatterCycleType(item.eDDate);
                    })
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.count, //解析数据长度
                        "data": res.data//解析数据列表
                    };
                }
            }
        });
    }

    //相同key 属性值相加
    function attrValueAdd(arry){
        var temp = {};
        for(var i in arry) {
            var key= arry[i].key;
            if(temp[key]) {
                temp[key].key = temp[key].key ;
                temp[key].value = parseInt(temp[key].value,10) + parseInt(arry[i].value,10);

            } else {
                temp[key] = {};
                temp[key].key = arry[i].key;
                temp[key].value = arry[i].value;

            }
        }
        return temp;
    }


    function initLayUI() {
        layui.use(['form', 'laydate', 'layer', 'table', 'element'], function () {
            var form = layui.form;
            var laydate = layui.laydate;
            var table = layui.table;
            var layer = layui.layer;
            var element = layui.element;
            var formSelects = layui.formSelects;
            //起止时间1
            laydate.render({
                elem: '#test1',
                type:'date'
                ,trigger: 'click'
            });
            //起止时间2
            laydate.render({
                elem: '#test2',
                type:'date'
                ,trigger: 'click'
            });

            for(var i in params){
                renderData(params[i].elem, params[i].url, params[i].title, params[i].height,params[i].cols,params[i].parseData, params[i].tableId, table, element, filterName);
            }
            renderData(params[0].elem, params[0].url, params[0].title,params[0].height, params[0].cols, params[0].parseData,params[0].tableId, table, element, filterName);


            //监听工具条
            table.on('tool(test)', function (obj) {
                var data = obj.data;
                if (obj.event === 'del') {
                    layer.confirm('真的删除行么', function (index) {
                        var objJson = {
                            id: data.id,
                            checkType: data.checkType
                        }
                        $.ajax({
                            type: 'POST',
                            data: objJson,
                            contentType:"application/x-www-form-urlencoded",
                            url: '${bathPath}/checkInOut/delete.action',
                            success: function (data) {
                                if (data == 'SUCCESS') {
                                    layer.close(index);
                                    //执行重载
                                    table.reload('statisticalRecords', {
                                        where: {
                                        }
                                        , page: {
                                            curr: 1
                                        }
                                    });
                                }
                            }
                        })
                    });
                } else if (obj.event === 'edit') {
                    //传入编辑逻辑事件
                    runEvent(data);
                } else if (obj.event === 'cancel') {
                    layer.close(layerIndex);
                }
            });

            form.on('select(business)', function (data) {
                //获取部门的ID通过异步查询子集
                var depId = $(this).attr("lay-value");
                $.ajax({
                    type: "POST",
                    async:false,
                    data: {depId:depId},
                    dataType:'json',
                    contentType:"application/x-www-form-urlencoded",
                    url: "${bathPath}/userInfo/selectUserName.action",
                    success: function (msg) {
                        var html = "";
                        html += "<option value=''>" + '请选择员工' + "</option>";
                        for (var i = 0; i < msg.length; i++) {
                            html += "<option value='" + msg[i].userID + "'>" + msg[i].userName + "</option>";
                        }
                        $("#userName").html(html);
                        form.render('select');
                        formSelects.render('userName');
                    }
                });
            });

            var runEvent = function (data) {
                //初始化表单值
                $('#userID').val(data.userID);
                $('#checkTime').val(data.checkTime);
                form.val('example', {
                    editStatus: data.editStatus
                })
                layerIndex = layer.open({
                    type: 1
                    , title: '修改出勤状态' //不显示标题栏
                    , area: '350px;'
                    ,skin:'demo-class'
                    , shade: 0.8
                    , id: 'LAY_layuipro2' //设定一个id，防止重复弹出
                    // ,btn: ['确定', '取消']
                    // ,btnAlign: 'c'
                    , moveType: 1 //拖拽模式，0或者1
                    , content: $('#addMask')
                    , success: function (layero, index) {
                        console.log(layero);
                        form.render();
                    }
                });
            }

            var $ = layui.$, active = {
                reload: function () {
                    var depId = $('#depId');
                    var userID = formSelects.value('userName', 'valStr');
                    var beginTime = $('#test1').val() ? $('#test1').val() + ' 00:00:00': '';
                    var endTime = $('#test2').val() ? $('#test2').val() + ' 11:59:59':'';
                    var id = $('#select').data('id') || 0;
                    var tableId = ids[id];
                    // //获取多选框的值
                    // var sort = [];
                    // $("input:checkbox[name='sort']:checked").each(function () {
                    //     sort.push($(this).val());
                    // })
                    //执行重载
                    table.reload(tableId, {
                        where: {
                            depId: depId.val(),
                            userID: userID,
                            startTime: beginTime,
                            endTime: endTime
                            // sort: sort.toString()
                        }
                        , page: {
                            curr: 1
                        }
                    });
                }
            };

            $('.demoTable .layui-btn').on('click', function () {
                var type = $(this).data('type');
                var id = $(this).data('id');
                active[type] ? active[type].call(this, id) : '';
            });

            $('.cancel-layer').on('click', function () {
                layer.close(layerIndex);
            })

            form.on('submit(formTest)', function (data) {
                // layer.alert(JSON.stringify((data.field), {
                //     title: '最终提交的信息'
                // }))
                var dataJson = data.field;
                dataJson.userID = $('#userID').val();
                dataJson.checkTime = $('#checkTime').val();
                $.ajax({
                    type: 'POST',
                    data: dataJson,
                    contentType:"application/x-www-form-urlencoded",
                    url: '${bathPath}/checkInOut/update.action',
                    success: function (data) {
                        if (data == 'SUCCESS') {
                            layer.close(layerIndex);
                            //执行重载
                            table.reload('statisticalRecords', {
                                where: {
                                }
                                , page: {
                                    curr: 1
                                }
                            });
                        }
                    }
                })
                return false;
            })
        });
    }

    function renderData(elem, url, title, height, cols,parseData, tableId, table, element, filterName) {
        table.render({
            elem: elem
            , url: url
            ,height:height
            , toolbar: true
            , title: title
            , cols: [cols]
            , page: true
            , response: {
                statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            , id: tableId
            ,parseData:parseData
            // , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            //     return {
            //         "code": res.status, //解析接口状态
            //         "msg": res.message, //解析提示文本
            //         "count": res.total, //解析数据长度
            //         "data": res.rows.item //解析数据列表
            //     };
            // }
        });
        element.on('tab(' + filterName + ')', function (data) {
            $('#select').data('id',data.index);
        });
    }
</script>
</html>